/**
 * @file lv_port_disp_templ.c
 *
 */

/*Copy this file as "lv_port_disp.c" and set this value to "1" to enable content*/
#if 1

/*********************
 *      INCLUDES
 *********************/
#include <rtdevice.h>
#include "lv_port_disp.h"
#include <stdbool.h>

#define MY_DISP_HOR_RES LV_HOR_RES
#define MY_DISP_VER_RES LV_VER_RES
/*********************
 *      DEFINES
 *********************/
#ifndef MY_DISP_HOR_RES
    #warning Please define or replace the macro MY_DISP_HOR_RES with the actual screen width, default value 320 is used for now.
    #define MY_DISP_HOR_RES    800
#endif

#ifndef MY_DISP_VER_RES
    #warning Please define or replace the macro MY_DISP_HOR_RES with the actual screen height, default value 240 is used for now.
    #define MY_DISP_VER_RES    480
#endif


static rt_device_t device;
static struct rt_device_graphic_info info;
//static struct rt_messagequeue *input_mq;
//static int _lv_init = 0;
typedef struct{
    uint8_t blue;
    uint8_t green;
    uint8_t red;
} lv_color24_t;

static void color_to16_maybe(lv_color16_t *dst, lv_color_t *src){
#if (LV_COLOR_DEPTH == 16)
    dst->full = src->full;
#else
    dst->ch.blue = src->ch.blue;
    dst->ch.green = src->ch.green;
    dst->ch.red = src->ch.red;
#endif
}

static void color_to24(lv_color24_t *dst, lv_color_t *src){
    dst->blue = src->ch.blue;
    dst->green = src->ch.green;
    dst->red = src->ch.red;
}

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void disp_init(void);

static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p);
//static void gpu_fill(lv_disp_drv_t * disp_drv, lv_color_t * dest_buf, lv_coord_t dest_width,
//        const lv_area_t * fill_area, lv_color_t color);

/**********************
 *  STATIC VARIABLES
 **********************/

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

void lv_port_disp_init(void){
    /*-------------------------
     * Initialize your display
     * -----------------------*/
    disp_init();

    /*-----------------------------
     * Create a buffer for drawing
     *----------------------------*/

    /**
     * LVGL requires a buffer where it internally draws the widgets.
     * Later this buffer will passed to your display driver's `flush_cb` to copy its content to your display.
     * The buffer has to be greater than 1 display row
     *
     * There are 3 buffering configurations:
     * 1. Create ONE buffer:
     *      LVGL will draw the display's content here and writes it to your display
     *
     * 2. Create TWO buffer:
     *      LVGL will draw the display's content to a buffer and writes it your display.
     *      You should use DMA to write the buffer's content to the display.
     *      It will enable LVGL to draw the next part of the screen to the other buffer while
     *      the data is being sent form the first buffer. It makes rendering and flushing parallel.
     *
     * 3. Double buffering
     *      Set 2 screens sized buffers and set disp_drv.full_refresh = 1.
     *      This way LVGL will always provide the whole rendered screen in `flush_cb`
     *      and you only need to change the frame buffer's address.
     */

    /* Example for 1) */
#if 1
    static lv_disp_draw_buf_t draw_buf_dsc_1;
    static lv_color_t buf_1[MY_DISP_HOR_RES * MY_DISP_VER_RES];                          /*A buffer for 10 rows*/
    lv_disp_draw_buf_init(&draw_buf_dsc_1, buf_1, NULL, MY_DISP_HOR_RES * MY_DISP_VER_RES);   /*Initialize the display buffer*/
#else
    /* Example for 2) */
    static lv_disp_draw_buf_t draw_buf_dsc_2;
    static lv_color_t buf_2_1[MY_DISP_HOR_RES * 10];                        /*A buffer for 10 rows*/
    static lv_color_t buf_2_2[MY_DISP_HOR_RES * 10];                        /*An other buffer for 10 rows*/
    lv_disp_draw_buf_init(&draw_buf_dsc_2, buf_2_1, buf_2_2, MY_DISP_HOR_RES * 10);   /*Initialize the display buffer*/

    /* Example for 3) also set disp_drv.full_refresh = 1 below*/
    static lv_disp_draw_buf_t draw_buf_dsc_3;
    static lv_color_t buf_3_1[MY_DISP_HOR_RES * MY_DISP_VER_RES];            /*A screen sized buffer*/
    static lv_color_t buf_3_2[MY_DISP_HOR_RES * MY_DISP_VER_RES];            /*Another screen sized buffer*/
    lv_disp_draw_buf_init(&draw_buf_dsc_3, buf_3_1, buf_3_2,
            MY_DISP_HOR_RES * MY_DISP_VER_RES/*MY_DISP_VER_RES * LV_VER_RES_MAX*/);   /*Initialize the display buffer*/
#endif

    /*-----------------------------------
     * Register the display in LVGL
     *----------------------------------*/

    static lv_disp_drv_t disp_drv;                         /*Descriptor of a display driver*/
    lv_disp_drv_init(&disp_drv);                    /*Basic initialization*/

    /*Set up the functions to access to your display*/

    /*Set the resolution of the display*/
#ifdef LV_VERTICAL_DISPLAY
    disp_drv.hor_res = MY_DISP_VER_RES;
    disp_drv.ver_res = MY_DISP_HOR_RES;
#else
    disp_drv.hor_res = MY_DISP_HOR_RES;
    disp_drv.ver_res = MY_DISP_VER_RES;
#endif
    /*Used to copy the buffer's content to the display*/
    disp_drv.flush_cb = disp_flush;

    /*Set a display buffer*/
    disp_drv.draw_buf = &draw_buf_dsc_1;//&draw_buf_dsc_1;//

    /*Required for Example 3)*/
    //disp_drv.full_refresh = 1;

    /* Fill a memory array with a color if you have GPU.
     * Note that, in lv_conf.h you can enable GPUs that has built-in support in LVGL.
     * But if you have a different GPU you can use with this callback.*/
    //disp_drv.gpu_fill_cb = gpu_fill;
/*
#if defined LV_VERTICAL_DISPLAY
    disp_drv.sw_rotate = 1;   // add for rotation
    disp_drv.rotated = LV_DISP_ROT_90;   // add for rotation
#endif
*/
    /*Finally register the driver*/
    lv_disp_drv_register(&disp_drv);
}

/**********************
 *   STATIC FUNCTIONS
 **********************/

/*Initialize your display and the required peripherals.*/
static void disp_init(void){
    /*You code here*/
    device = rt_device_find("lcd");
    RT_ASSERT(device != RT_NULL);
    if (rt_device_open(device, RT_DEVICE_OFLAG_RDWR) == RT_EOK){
        rt_device_control(device, RTGRAPHIC_CTRL_GET_INFO, &info);
    }
}

volatile bool disp_flush_enabled = true;

/* Enable updating the screen (the flushing process) when disp_flush() is called by LVGL
 */
void disp_enable_update(void){
    disp_flush_enabled = true;
}

/* Disable updating the screen (the flushing process) when disp_flush() is called by LVGL
 */
void disp_disable_update(void){
    disp_flush_enabled = false;
}


/*Flush the content of the internal buffer the specific area on the display
 *You can use DMA or any hardware acceleration to do this operation in the background but
 *'lv_disp_flush_ready()' has to be called when finished.*/
static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p){
    //rt_kprintf("disp_flush disp_flush \n");
#if 0
    if(disp_flush_enabled) {
        /*The most simple case (but also the slowest) to put all pixels to the screen one-by-one*/
        int32_t x;
        int32_t y;
        for(y = area->y1; y <= area->y2; y++) {
            for(x = area->x1; x <= area->x2; x++) {
                /*Put a pixel to the display. For example:*/
                /*put_px(x, y, *color_p)*/
                color_p++;
            }
        }
    }
#endif
#if 0
	int x1, x2, y1, y2;
        x1 = area->x1;
        x2 = area->x2;
        y1 = area->y1;
        y2 = area->y2;
        rt_kprintf("x1=%d x2=%d y1=%d y2=%d w=%d h=%d \n",x1,x2,y1,y2,info.width,info.height);
        /*Return if the area is out the screen*/
        if (x2 < 0)
            return;
        if (y2 < 0)
            return;
        if (x1 > info.width - 1)
            return;
        if (y1 > info.height - 1)
            return;
        rt_kprintf("x1=%d x2=%d y1=%d y2=%d \n",x1,x2,y1,y2);
        /*Truncate the area to the screen*/
        int32_t act_x1 = x1 < 0 ? 0 : x1;
        int32_t act_y1 = y1 < 0 ? 0 : y1;
        int32_t act_x2 = x2 > info.width - 1 ? info.width - 1 : x2;
        int32_t act_y2 = y2 > info.height - 1 ? info.height - 1 : y2;
        uint32_t x;
        uint32_t y;
        long int location = 0;

        if (info.bits_per_pixel == 8){
            uint8_t *fbp8 = (uint8_t *)info.framebuffer;
            for (y = act_y1; y <= act_y2; y++){
                for (x = act_x1; x <= act_x2; x++){
                    location = (x) + (y)*info.width;
                    fbp8[location] = color_p->full;
                    color_p++;
                }
                color_p += x2 - act_x2;
            }
        }else if (info.bits_per_pixel == 16){
            lv_color16_t *fbp16 = (lv_color16_t *)info.framebuffer;
            for (y = act_y1; y <= act_y2; y++){
                for (x = act_x1; x <= act_x2; x++){
                    location = (x) + (y)*info.width;
                    color_to16_maybe(&fbp16[location], color_p);
                    color_p++;
                }
                color_p += x2 - act_x2;
            }
        }else if (info.bits_per_pixel == 24){
            lv_color24_t *fbp24 = (lv_color24_t *)info.framebuffer;
            for (y = act_y1; y <= act_y2; y++){
                for (x = act_x1; x <= act_x2; x++){
                    location = (x) + (y)*info.width;
                    color_to24(&fbp24[location], color_p);
                    color_p++;
                }
                color_p += x2 - act_x2;
            }
        }else if (info.bits_per_pixel == 32){
            uint32_t *fbp32 = (uint32_t *)info.framebuffer;
            for (y = act_y1; y <= act_y2; y++){
                for (x = act_x1; x <= act_x2; x++){
                    location = (x) + (y)*info.width;
                    fbp32[location] = color_p->full;
                    color_p++;
                }
                color_p += x2 - act_x2;
            }
        }

        struct rt_device_rect_info rect_info;
        rect_info.x = x1;
        rect_info.y = y1;
        rect_info.width = x2 - x1 + 1;
        rect_info.height = y2 - y1 + 1;
        rt_device_control(device, RTGRAPHIC_CTRL_RECT_UPDATE, &rect_info);
		rt_kprintf("lv_disp_flush_ready \n");
    /*IMPORTANT!!!
     *Inform the graphics library that you are ready with the flushing*/
#endif
#ifndef LV_VERTICAL_DISPLAY
    /*Return if the area is out the screen*/
    lv_coord_t hres = disp_drv->rotated == 0 ? disp_drv->hor_res : disp_drv->ver_res;
    lv_coord_t vres = disp_drv->rotated == 0 ? disp_drv->ver_res : disp_drv->hor_res;
    /*Return if the area is out the screen*/
    if (area->x2 < 0 || area->y2 < 0 || area->x1 > hres - 1 || area->y1 > vres - 1){
        lv_disp_flush_ready(disp_drv);
        return;
    }
    int32_t y;
    #if LV_COLOR_DEPTH == 24 || LV_COLOR_DEPTH == 32    /*32 is valid but support 24 for backward compatibility too*/
    uint32_t w = lv_area_get_width(area);
    uint32_t *fbp32 = (uint32_t*) info.framebuffer;
    for (y = area->y1; y <= area->y2 && y < disp_drv->ver_res; y++){
        memcpy(&fbp32[y * info.width + area->x1], color_p, w * sizeof(lv_color_t));
        color_p += w;
    }
    #else
    int32_t x;
    uint32_t w = lv_area_get_width(area);
    uint16_t *fbp32 = (uint16_t*) info.framebuffer;
    for (y = area->y1; y <= area->y2 && y < disp_drv->ver_res; y++){
        memcpy(&fbp32[y * info.width + area->x1], color_p, w * sizeof(lv_color_t));
        color_p += w;
    }
    #endif
#else
 int32_t     y;
 int32_t     x;
 int32_t     ys;
 int32_t     xs;
 uint32_t    w;
 uint32_t    ulSource;
 uint32_t    ulDest;

 uint32_t *fbp32 = (uint32_t*) info.framebuffer;
 lv_coord_t hres = disp_drv->rotated == 0 ? disp_drv->hor_res : disp_drv->ver_res;
     lv_coord_t vres = disp_drv->rotated == 0 ? disp_drv->ver_res : disp_drv->hor_res;
 if (area->x2 < 0 || area->y2 < 0 || area->x1 > hres - 1 || area->y1 > vres - 1){
         lv_disp_flush_ready(disp_drv);
         return;
     }

 w = lv_area_get_width (area);

 for (x = area->x1, xs = 0; x <= area->x2; x++, xs++) {                  // Copy the area data rotated into frame buffer 1.
 for (y = area->y1, ys = 0; y <= area->y2; y++, ys++) {
   ulSource = (uint32_t) color_p    + ((xs + (ys * w)) * sizeof (lv_color_t));
   ulDest   = (uint32_t) fbp32 + ((y  + ((disp_drv->hor_res - 1 - x) * disp_drv->ver_res)) * sizeof (lv_color_t));

   if (sizeof (lv_color_t) == 4)  {
  *((uint32_t*) ulDest) = *((uint32_t*) ulSource);
   }
   else if (sizeof (lv_color_t) == 2)  {
  *((uint16_t*) ulDest) = *((uint16_t*) ulSource);
   }
   else {
   *((uint8_t*) ulDest) = *((uint8_t*) ulSource);
   }
 }
 }
#endif
    struct rt_device_rect_info rect_info;
    rect_info.x = area->x1;
    rect_info.y = area->y1;
    rect_info.width = area->x2 - area->x1;
    rect_info.height = area->y2 - area->y1;
    rt_device_control(device, RTGRAPHIC_CTRL_RECT_UPDATE, &rect_info);
    //rt_kprintf("lv_disp_flush_ready \n");
    lv_disp_flush_ready(disp_drv);
}

/*OPTIONAL: GPU INTERFACE*/

/*If your MCU has hardware accelerator (GPU) then you can use it to fill a memory with a color*/
//static void gpu_fill(lv_disp_drv_t * disp_drv, lv_color_t * dest_buf, lv_coord_t dest_width,
//                    const lv_area_t * fill_area, lv_color_t color)
//{
//    /*It's an example code which should be done by your GPU*/
//    int32_t x, y;
//    dest_buf += dest_width * fill_area->y1; /*Go to the first line*/
//
//    for(y = fill_area->y1; y <= fill_area->y2; y++) {
//        for(x = fill_area->x1; x <= fill_area->x2; x++) {
//            dest_buf[x] = color;
//        }
//        dest_buf+=dest_width;    /*Go to the next line*/
//    }
//}


#else /*Enable this file at the top*/

/*This dummy typedef exists purely to silence -Wpedantic.*/
typedef int keep_pedantic_happy;
#endif
